<?php

namespace Admin\Model\DBO;

use Zend\Db\TableGateway\AbstractTableGateway;
use Admin\Entity\SerialBook;

class StoringBookDBO extends AbstractTableGateway {

    private $sm;
    private $serialBookTable;
    private $bookStoreTable;
    public function __construct($serviceManager) {
        $this->sm = $serviceManager;
    }

    public function getSerialBookTable() {
        if (!$this->serialBookTable) {
            $this->serialBookTable = $this->sm->get('Admin\Model\DAO\SerialBookTable');
        }
        return $this->serialBookTable;
    }

    public function getBookStoreTable() {
        if (!$this->bookStoreTable) {
            $this->bookStoreTable = $this->sm->get('Admin\Model\DAO\BookStoreTable');
        }
        return $this->bookStoreTable;
    }

    public function saveSerialBook(SerialBook $serialBook) {
        // xu ly ma barcode
        $bookBarcode = explode('-', $serialBook->getBookBarcode());
        $serial = array_pop($bookBarcode);
        $serialBook->setBookBarcode($bookBarcode['0']);
        $serialBook->setSerial($serial);
        $serialBook->setDateCreated(date('Y-m-d'));
        $serialBook->setBookStatus('0');
        $message = "";
        // Kiem tra xem cuon sach nay da duoc bien muc hay chua (ton tai ma barcode trong lib_bookStore)
        $result = $this->getBookStoreTable()->getBookBarcode($serialBook->getBookBarcode());
        if($result) {
            $result = $this->getSerialBookTable()->getBookID($bookBarcode['0'],$serial);
            if(!$result) {
                 if($this->getSerialBookTable()->saveSerialBook($serialBook)) {
                     $message = "storeOk";
                 }
                else {
                    $message = "storeError";
                }
            }
            else {
                $message = "bookExist";
            }
        }
        else {
            // Kiem tra xem cap barCode va serial da tont tai trong bang lib_serialBook hay chua
            return "barcodeNotExist";
        }
        return $message;
    }

}